package com.qf.taobei.service.impl;

import com.qf.taobei.entity.Discount;
import com.qf.taobei.entity.RespBean;
import com.qf.taobei.entity.vo.ViewDiscount;
import com.qf.taobei.mapper.DiscountMapper;
import com.qf.taobei.service.DiscountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DiscountServiceImpl implements DiscountService {

    @Autowired
    private DiscountMapper discountMapper;

    //根据优惠券id查询优惠券信息
    @Override
    public Discount queryDiscountById(Integer id) {
        return discountMapper.queryDiscountById(id);
    }

    //修改优惠券信息
    @Override
    public Integer updateDiscount(Discount discount) {
        return discountMapper.updateDiscount(discount);
    }

    //用户领取优惠券
    @Transactional
    @Override
    public Integer getDis(Integer uid, Integer id) {
        //先修改优惠券的库存
        Integer res = discountMapper.updateRepertory(id);
        if (res == 0)
            return res;
        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        //添加用户和优惠券的关联
        res = discountMapper.addUserDis(uid, id, time);
        if (res == 0)
            throw new RuntimeException("出现问题");
        return res;
    }

    @Transactional
    @Override
    public Integer delDiscount(Integer id) {
        //先将用户和优惠券的关系删除
        discountMapper.delUserDis(id);
        //删除优惠券信息
        discountMapper.delDiscount(id);
        return 1;
    }

    //添加优惠券
    @Override
    public Integer addDiscount(HttpServletRequest request,Discount discount) {
        Integer storeId = (Integer) request.getSession().getAttribute("storeId");
        Date date = new Date();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        String time = simpleDateFormat.format(date);
        discount.setReleaseTime(time);
        discount.setSid(storeId);
        return discountMapper.addDiscount(discount);
    }

    @Override
    public List<ViewDiscount> queryAllDiscount() {
        return discountMapper.queryAllDiscount();
    }

    @Override
    public List<ViewDiscount> queryDiscountByUid(Integer id) {
        return discountMapper.qeuryDiscountByUid(id);
    }

    @Override
    public List<ViewDiscount> getDiscBySid(Integer id) {
        return discountMapper.queryDiscountBySid(id);
    }

    @Override
    public List<ViewDiscount> queryDiscountByPId(Integer pid) {
        return discountMapper.queryDiscountByPId(pid);
    }
}
